package com.Yukiha.gachamod.Data;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.saveddata.SavedData;

import java.util.*;

public class GachaSavedData extends SavedData {
    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
    private final Map<UUID, PlayerGachaData> playerData = new HashMap<>();

    @Override
    public CompoundTag save(CompoundTag tag) {
        JsonObject root = new JsonObject();
        for (Map.Entry<UUID, PlayerGachaData> entry : playerData.entrySet()) {
            root.add(entry.getKey().toString(), entry.getValue().toJson());
        }
        tag.putString("data", GSON.toJson(root));
        return tag;
    }

    public static GachaSavedData load(CompoundTag tag) {
        GachaSavedData data = new GachaSavedData();
        if (tag.contains("data")) {
            JsonObject root = GSON.fromJson(tag.getString("data"), JsonObject.class);
            for (Map.Entry<String, JsonElement> entry : root.entrySet()) {
                UUID uuid = UUID.fromString(entry.getKey());
                data.playerData.put(uuid, PlayerGachaData.fromJson(entry.getValue().getAsJsonObject()));
            }
        }
        return data;
    }

    public PlayerGachaData getPlayerData(UUID uuid) {
        return playerData.computeIfAbsent(uuid, id -> new PlayerGachaData());
    }

    public static GachaSavedData get(ServerLevel level) {
        return level.getDataStorage().computeIfAbsent(
                GachaSavedData::load,
                GachaSavedData::new,
                "gacha_data"
        );
    }

    public void removeModel(UUID uuid, String modelId) {
        PlayerGachaData data = getPlayerData(uuid);
        data.removeModel(modelId);
        this.setDirty();
    }

    public Set<String> getModels(UUID uuid) {
        return getPlayerData(uuid).getAllDrawnModels();
    }

    public void addModel(UUID uuid, String modelId) {

    }
}



